package com.zqh.forum.controller;

import com.zqh.forum.common.AppResult;
import com.zqh.forum.common.ResultCode;
import com.zqh.forum.config.AppConfig;
import com.zqh.forum.exception.ApplicationException;
import com.zqh.forum.model.User;
import com.zqh.forum.services.IUserService;
import com.zqh.forum.utils.MD5Util;
import com.zqh.forum.utils.UUIDUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@Slf4j
//这是一个返回数据的controller
@Tag(name = "用户接口")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;
    /**
     * 用户注册
     * @param username 用户名
     * @param nickname 用户昵称
     * @param password 密码
     * @param passwordRequest 确认密码
     * @return
     */

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    //对各个元素进行描述
    @Parameters({
            @Parameter(name = "username",description = "用户名"),
            @Parameter(name = "nickname",description = "昵称"),
            @Parameter(name = "password",description = "密码"),
            @Parameter(name = "passwordRequest",description = "确认密码")
    })
    public AppResult register(@RequestParam("username") @NonNull String username,
                              @RequestParam("nickname") @NonNull String nickname,
                              @RequestParam("password") @NonNull String password,
                              @RequestParam("passwordRequest") @NonNull String passwordRequest){
        //非空校验
//        if(!StringUtils.hasLength(username) ||
//                !StringUtils.hasLength(nickname) ||
//                !StringUtils.hasLength(password) ||
//                !StringUtils.hasLength(passwordRequest)){
//            //信息不准确
//            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
//        }
        //校验两次的密码是否一致
        if(!password.equals(passwordRequest)){
            //不一致
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //生成盐
        String salt = UUIDUtil.UUID_32();
        //对密码进行加密操作(密文)
        String cip = MD5Util.md5_salt(password, salt);
        //准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        user.setPassword(cip);
        user.setSalt(salt);
        //调用service层
        userService.createNormalUser(user);
        //返回结果
        return AppResult.success();
    }

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    //对元素的描述
    @Parameters({
            @Parameter(name = "username",description = "用户名"),
            @Parameter(name = "password",description = "密码")
    })
    public AppResult login(HttpServletRequest request,
                           @RequestParam("username") @NonNull String username,
                           @RequestParam("password") @NonNull String password){
        //1.调用service中的处理逻辑
        User user = userService.login(username,password);
        if(user == null){
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //返回结果
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //2.将登录成功的用户信息user存储在session中
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        //3.返回结果
        return AppResult.success();
    }


    /**
     * 根据用户id查询用户信息
     * @param request 要是没有id的话就在session中获取已经登录的用户的信息
     * @param id 用户的id
     * @return 返回json格式的结果
     */
    @GetMapping("/info")
    @Operation(summary = "获取用户的详情信息")
    @Parameter(name = "id",description = "用户的id")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @RequestParam(value = "id",required = false) Long id){
        User user = null;
        //1.非空校验
        if(id == null){
            //id为null,获取登录的用户信息
            HttpSession session = request.getSession(false);

            //从session中获取用户的信息
            user = (User)session.getAttribute(AppConfig.USER_SESSION);
        }else{
            //存在id,从数据中查找用户信息
            user = userService.selectById(id);
        }
        //判断用户信息是否存在
        if(user == null){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //存在返回正常的结果
        return AppResult.success(user);
    }

    @Operation(summary = "退出登录")
    @GetMapping("/logout")
    public AppResult logout (HttpServletRequest request){
        //获取登录的session对象
        HttpSession session = request.getSession(false);
        //判断session是否有效
        if(session != null){
            //有效，用户在登录状态
            //打印日志
            log.info("退出成功");
            session.invalidate(); //销毁session
        }
        return AppResult.success("登录成功");
    }

    /**
     * 修改个人信息
     * @param username  用户名
     * @param nickname  昵称
     * @param gender 性别
     * @param email 邮箱
     * @param phoneNum 电话号
     * @param remark 个人简介
     * @return
     */
    @Operation(summary = "修改用户的个人信息")
    @PostMapping("/modifyInfo")
    @Parameters({
            @Parameter(name = "username" ,description = "用户名"),
            @Parameter(name = "nickname" ,description = "昵称"),
            @Parameter(name = "gender" ,description = "性别"),
            @Parameter(name = "email" ,description = "邮箱"),
            @Parameter(name = "phoneNum" ,description = "电话号"),
            @Parameter(name = "remark" ,description = "个人简介")
    })
    public AppResult modifyInfo (HttpServletRequest request,
                                 @RequestParam(value = "username",required = false) String username,
                                 @RequestParam(value = "nickname",required = false) String nickname,
                                 @RequestParam(value = "gender",required = false) Byte gender,
                                 @RequestParam(value = "email",required = false) String email,
                                 @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                 @RequestParam(value = "remark",required = false) String remark){
        //非空校验
        if(!StringUtils.hasLength(username) && !StringUtils.hasLength(nickname) &&
                !StringUtils.hasLength(phoneNum) && !StringUtils.hasLength(remark) &&
                !StringUtils.hasLength(email) && gender != null){
            //返回错误信息
            return AppResult.failed("请输入要修改的内容");
        }
        //获取session的登录对象
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //封装要修改的对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        //调用services层
        userService.modifyInfo(updateUser);
        //查询用户的最新信息
        user = userService.selectById(user.getId());
        //把最新的用户信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION,user);
        //返回结果
        return AppResult.success(user);
    }

    /**
     * 修改密码
     * @param passwordRepeat 确认新密码
     * @param newPassword 新密码
     * @param oldPassword 旧密码
     * @return
     */
    @Operation(summary = "修改密码")
    @PostMapping("/modifyPwd")
    @Parameters({
            @Parameter(name = "passwordRepeat",description = "确认新密码"),
            @Parameter(name = "newPassword",description = "新密码"),
            @Parameter(name = "oldPassword",description = "旧密码")
    })
    public AppResult modifyPassword(HttpServletRequest request,
                                    @RequestParam("passwordRepeat") @NonNull String passwordRepeat,
                                    @RequestParam("newPassword") @NonNull String newPassword,
                                    @RequestParam("oldPassword") @NonNull String oldPassword){
        //1.判断两次密码是否一样
        if(!newPassword.equals(passwordRepeat)){
            //密码不一样
            return  AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //2.从session中获取用户的信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //3.调用service层
        userService.modifyPassword(user.getId(),newPassword,oldPassword);

        //4.修改成功，销毁session再次登录
        if(session != null){
            session.invalidate();
        }
        //5.返回结果
        return AppResult.success();
    }






}
